
<style lang="scss" scoped>
.scroll {
  height: 100%;
  overflow: auto;
  box-sizing: border-box;
}

.container {
  position: fixed;
  width: 100%;
  top: 70px;
  bottom: 0;
  background: #f0f0f0;
  ul {
    width: 100%;
    height: auto;
    padding: 0 10px 0px;
  }
  .pro-info {
    margin-left: 10px;
  }
  .item-count {
    width: 100%;
    height: 25px;
    position: relative;
    margin-top: 5px;
  }

  .hidden {
    display: none;
  }

  .item-hand {
    position: relative;
    margin-right: 10px;
  }

  .item-hand__bg {
    background: rgba(255, 137, 156, 1);
    opacity: 0.2;
    width: 75px;
    height: 20px;
    z-index: 10;
    border-radius: 10px;
  }

  .item-hand__it {
    position: absolute;
    right: 0px;
    height: 20px;
    width: 71px;
    top: 0px;
  }

  .item-hand__it i {
    width: 22px;
    height: 22px;
    display: inline-block;
    vertical-align: middle;
  }

  .item-hand__it i.add {
    background: url("/static/ethel_img/shop/but_plus_usable@2x.png") center
      center no-repeat;
    background-size: 100% 100%;
    vertical-align: middle;
    z-index: 100;
  }

  .item-hand__it input {
    outline: none;
    border: none;
    width: 100%;
    height: 100%;
    font-size: 12px;
    text-align: center;
  }

  .item-hand__it i.dect {
    background: url("/static/ethel_img/shop/but_subtract_usable@2x.png") center
      center no-repeat;
    background-size: 100% 100%;
    vertical-align: middle;
    margin-left: -4px;
    z-index: 100;
  }
}
footer {
  width: 100%;
  height: 50px;
  line-height: 50px;
  position: fixed;
  left: 0px;
  bottom: 0px;
  right: 0px;
  background: #fff;
  box-sizing: border-box;
  padding-left: 12px;
  z-index: 1000;
}

footer > span {
  box-sizing: border-box;
  font-size: 14px;
}

footer > span::before {
  width: 17px;
  height: 17px;
  content: "";
  display: inline-block;
  border-radius: 50%;
  border: 1px solid #e5e5e5;
  margin-right: 5px;
  vertical-align: middle;
}

footer > span.active::before {
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  border: none;
}

footer > div > span {
  font-size: 12px;
  color: rgba(160, 154, 155, 1);
  margin-right: 7px;
}

footer > div > font {
  font-size: 16px;
  margin-right: 8px;
}

footer > div > div {
  width: 125px;
  height: 100%;
  text-align: center;
  font-size: 14px;
  color: #fff;
}

.cart-box {
  position: relative;
  height: auto;
  padding: 0px 0px;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
}

.cart-box .item {
  width: 135%;
  height: 124px;
  background: #fff;
  border-radius: 3px;
}

.item > div {
  -webkit-transition: all 0.3s linear;
  transition: all 0.3s linear;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  height: 100%;
}

.scroll-list__item {
  width: 87%;
  box-sizing: border-box;
  background: #fff;
}

.item > div > i {
  width: 24%;
  text-align: center;
  height: 100%;
  font-size: 14px;
  line-height: 87px;
  font-style: normal;
  position: relative;
  color: rgba(255, 161, 176, 1);
  background: rgba(255, 161, 176, 1);
}

.item > div > i::before {
  display: inline-block;
  width: 24px;
  height: 24px;
  content: "";
  background: url("/static/ethel_img/shop/learning_but_delete@2x.png") center
    center no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
  position: absolute;
  left: 50%;
  margin-left: -12px;
  top: 50%;
  margin-top: -12px;
}

.swipeleft {
  transform: translateX(-24%);
  -webkit-transform: translateX(-24%);
}

.item-sel {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 1px solid #e5e5e5;
  margin-right: 12px;
  margin-left: 2px;
  box-sizing: border-box;
}

.item-sel.active {
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
  border: none;
}

.scroll-list__item > img {
  width: 57px;
  height: 65px;
  display: inline-block;
  margin-right: 12px;
}

.item-spec {
  margin-top: 8px;
  display: inline-block;
  max-width: 70px;
  height: 20px;
  line-height: 20px;
  background: rgba(249, 249, 249, 1);
  border-radius: 2px;
  text-align: center;
  font-size: 12px;
  color: rgba(160, 154, 155, 1);
}

.item-spec::after {
  content: "";
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-left: 5px;
  background: url("/static/ethel_img/shop/icon_arrow.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
}

.item-info {
  box-sizing: border-box;
  padding: 10px 10px 10px 0;
}

.item-info > p {
  line-height: 20px;
}

.item-count {
  width: 100%;
  height: 25px;
  position: relative;
  margin-top: 5px;
}
.notMore {
  width: 100%;
  height: 100%;
  padding-top: 70px;
  span {
    font-size: 13px;
    color: rgba(160, 154, 155, 1);
    margin-top: 15px;
  }
  img {
    width: 140px;
    height: 85px;
    display: block;
  }
}
span.integral::before {
  content: "";
  width: 20px;
  height: 20px;
  display: inline-block;
  background: url("/static/ethel_img/order_icon_integral.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
}
._standard > span {
  font-size: 12px;
  height: 30px;
  line-height: 30px;
  background: #e5e5e5;
  padding: 5px;
}
.store-box {
  width: 100%;
  height: auto;
  margin-top: 15px;
}

.store-box__li {
  position: relative;
  margin-bottom: 15px;
  background: #fff;
}

.store-box__li > p {
  width: 100%;
  height: 43px;
  padding-left: 12px;
  font-size: 12px;
}

.store-box__li > p > i.store-box__icon {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 1px solid #e5e5e5;
  margin-right: 12px;
  box-sizing: border-box;
  display: inline-block;
}

.store-box__li > p > i.store-box__icon.active {
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  border: none;
}

.store-box__li > p > .storeAvatar {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url("/static/ethel_img/shop/order_icon_shop@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
  margin-right: 9px;
}
</style>

<template>
  <div class="withdrawal">
    <ComHeader title="购物车" leftArrow="true"/>
    <div class="container" v-if="shopList && shopList.length">
      <scroll
        class="scroll"
        :data="drawalList"
        :pullup="isPullup"
        @scrollToEnd="searchMore"
        ref="suggest"
      >
        <ul class="store-box" v-if="shopList && shopList.length">
          <li
            class="store-box__li"
            v-for="(parentItem, parentIndex) in shopList"
            :key="parentIndex"
          >
            <p class="flex-display flex-center-align">
              <i
                class="store-box__icon"
                @click="fnSelectStore(parentItem)"
                :class="{'active': parentItem.select}"
              ></i>
              <span class="storeAvatar"></span>
              <span>{{parentItem.storeName}}</span>
            </p>
            <ul class="cart-box">
              <li class="item" v-for="(item, index) in parentItem.goods_data" :key="index">
                <div class="scroll-list">
                  <div class="scroll-list__item flex-display flex-center-align">
                    <span
                      class="item-sel"
                      :class="{'active': item.select}"
                      @click="fnHandleSelect(item, parentItem.storeId)"
                    ></span>
                    <img :src="item.goods_photo">
                    <div class="item-info flex-num-one flex-display flex-display-column">
                      <p class="text-overflow-2 f-12">{{item.goods_nickname}}</p>
                      <div class="item-count flex-display flex-center-align">
                        <span
                          v-if="item.goodsrebate[0].pay_type == '积分'"
                          class="integral"
                        >{{item.goods_discount_price}}积分</span>
                        <span v-else>￥{{item.goods_discount_price}}</span>
                        <div class="item-hand flex-num-one flex-display flex-right-pack">
                          <div class="item-hand__bg"></div>
                          <div class="item-hand__it flex-display flex-center-align">
                            <i class="dect" @click.stop.prevent="fnHandleQuantity(false,item)"></i>
                            <input
                              type="Number"
                              class="flex-num-one"
                              name="tel"
                              maxlength="4"
                              :value="item.quantity"
                              readonly="readonly"
                            >
                            <i class="add" @click="fnHandleQuantity(true,item)"></i>
                          </div>
                        </div>
                      </div>
                      <div class="_standard">
                        <span>{{item.standard}}</span>
                      </div>
                    </div>
                  </div>
                  <i :data-shopid="item.id">删除</i>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </scroll>
    </div>
    <footer class="flex-display flex-center-align">
      <span @click="fnHandleAllSelect" :class="{'active':isSleectAll}">全选</span>
      <div class="flex-display flex-right-pack flex-num-one" id="mentBtn">
        <span>合计：</span>
        <font class="theme-color">
          ￥
          <font>{{totalPrice}}</font>
        </font>
        <div class="theme-background" @click="fnOpenNewMakeOrder">
          结算(
          <span>{{isQuantity}}</span>)
        </div>
      </div>
    </footer>
    <div
      class="notMore flex-display flex-display-column flex-center-align"
      v-if="isLoading && !shopList.length"
    >
      <img src="/static/ethel_img/shopping_img_em.png">
      <span>购物车空空如也！！</span>
    </div>
  </div>
</template>
<script>
import api from "@/fetch/api";
import ComHeader from "@/common/ComHeader";
import Scroll from "@/base/scroll/scroll";
import Loading from "@/base/loading/loading";
import axios from "axios";
import { Toast, MessageBox, Indicator } from "mint-ui";

// 是否滑动展开
var expansion = null;
export default {
  data() {
    return {
      isHasMore: true, // 是否需要上拉加载
      drawalList: [], // 列表数据
      isPullup: true, // 是否需要监听下拉加载
      previous: null, // 是否还有下一页
      page: 1, // 页码
      limit: 10, // 条数
      totalPrice: 0, // 总价格
      isSleectAll: false,
      // 购物车数据列表
      shopList: [],
      isLoading: false
    };
  },
  created() {
    // 获取数据
    this.ethelWxUserInfo = this.getlocalStorage(this.companyUnique)
      ? this.getlocalStorage(this.companyUnique)
      : "";
    // 获取购物车列表
    this.fnGetShopList();
  },
  computed: {
    /**
     * @author yang
     * @dewsc 计算已经选择的数量
     */
    isQuantity() {
      let _len = 0;
      this.shopList.forEach(item => {
        item.goods_data.forEach(cel => {
          if (cel.select) {
            _len++;
          }
        });
      });
      return _len;
    }
  },
  mounted() {
    // 初始化滑动
  },
  methods: {
    /**
     * @author yang
     * @dews 选择店铺
     * @params {Ojbect} _parentItem 店铺对象
     */
    fnSelectStore(_parentItem) {
      _parentItem.select = !_parentItem.select;
      _parentItem.goods_data.forEach(item => {
        item.select = _parentItem.select;
      });
      // 计算总价
      this.fnHandleTotal();
    },

    fnAgencyid() {
      let params = {
        uid: this.ethelWxUserInfo.id
      };
      return new Promise((reslove, reject) => {
        api.agencyid(params).catch(res => {
          if (res.status == 200) {
            res.data.code == "1" ? reslove(false) : reslove(true);
          }
        });
      });
    },
    /**
     * @author yang
     * @dewsc 跳转到确定订单
     */
    async fnOpenNewMakeOrder() {
      if (!this.isQuantity) {
        Toast({
          message: "请选择商品",
          position: "middle",
          duration: 2000
        });
        return;
      }

      // 判断用户是否认证
      let isAudit = false;
      isAudit = await this.fnAgencyid();
      if (!isAudit) {
        Toast({
          message: "您当前还没认证",
          duration: 2000
        });
        setTimeout(() => {
          this.$router.push({
            name: 'NewAudit'
          })
        }, 1500)
        // 去认证
        return;
      }
      let intePay = 0;
      let wxPay = 0;
      var semList = [];
      var waterObj = {};
      for (let i = 0; i < this.shopList.length; i++) {
        for (let k = 0; k < this.shopList[i].goods_data.length; k++) {
          if (this.shopList[i].goods_data[k].select) {
            let key = this.shopList[i].storeId;
            if (!waterObj[key]) {
              waterObj[key] = {
                user: this.shopList[i].user,
                goods_data: [],
                storeName: this.shopList[i].storeName,
                storeId: this.shopList[i].storeId,
                freightValue: {}
              };
            }
            waterObj[key].goods_data.push(this.shopList[i].goods_data[k]);
          }
        }
      }
      for (let j in waterObj) {
        semList.push(waterObj[j]);
      }

      semList.forEach(item => {
        item.goods_data.forEach(childItem => {
          if (childItem.goodsrebate[0].pay_type == "积分") {
            intePay = 1;
          }
          if (childItem.goodsrebate[0].pay_type == "微信") {
            wxPay = 1;
          }
        });
      });
      let payTye = intePay && !wxPay ? 2 : !intePay && wxPay ? 1 : 3;

      if (payTye == 3) {
        Toast({
          message: "抱歉！不能同时选择支付类型不一样的商品",
          position: "middle",
          duration: 2000
        });
        return;
      }
      window.localStorage.setItem("pay_type", payTye);
      let payTyeName = payTye == 1 ? "微信" : "积分";
      this.$router.push({
        name: "NewMakeOrder",
        params: {
          list: semList,
          is_cart: "yes"
        }
      });
    },
    /**
     * @author yang
     * @dewsc 获取商品列表
     */
    fnGetShopList() {
      Indicator.open({
        text: "加载中...",
        spinnerType: "fading-circle"
      });
      api
        .goodscarcrud("get", { uid: this.ethelWxUserInfo.id })
        .catch(result => {
          Indicator.close();
          this.isLoading = true;
          if (result && result.data.code == 0 && result.data.data) {
            if (result.data.data && result.data.data.length) {
              result.data.data.forEach((item, index) => {
                item.select = false;
                item.goods_data.forEach(celItem => {
                  celItem.select = false;
                });
              });
              this.shopList = result.data.data;

              this.time = setTimeout(() => {
                this.fnInitListScroll();
                clearTimeout(this.time);
              }, 1000);
            }
          }
        });
    },
    /**
     * @author yang
     * @dewsc 点击全新按钮 操作是否全选
     */
    fnHandleAllSelect() {
      this.isSleectAll = !this.isSleectAll;
      this.shopList.forEach(item => {
        item.select = this.isSleectAll;
        item.goods_data.forEach(childItem => {
          childItem.select = item.select;
        });
      });
      this.fnHandleTotal();
    },

    /**
     * @author yang
     * @dewsc 点击全新按钮 操作是否全选
     */
    fnHandleSelect(item, storeId) {
      item.select = !item.select;
      // 获取所在店铺列表长度
      let _len = 0;
      let totLen = 0;
      let _item = null;
      this.shopList.forEach(item => {
        _item = item;
        if (item.storeId == storeId) {
          totLen = item.goods_data.length;
          _len = item.goods_data.filter(cle => {
            return cle.select;
          }).length;
        }
      });
      _item.select = _len == totLen ? true : false;
      // 计算总价格
      this.fnHandleTotal();
    },

    /**
     * @author yang
     * @param {Boolean} 是否是减还是加 false 减 true 加
     * @param {Object} item 当前对象
     */
    fnHandleQuantity(_isFlag, item) {
      if(item.select){
        _isFlag && item.quantity++;
        !_isFlag && item.quantity > 1 && item.quantity--;
        this.fnHandleTotal();
        // 调用更新接口
        this.fnHnadleUpdate(item);
      }else{
        Toast('请先勾选商品再操作')
      }
    },

    /**
     * @author yang
     * @param {Object} item 当前对象
     */
    fnHnadleUpdate(item) {
      api
        .goodscarcrud(
          "get",
          {
            uid: this.ethelWxUserInfo.id,
            quantity: item.quantity
          },
          item.id
        )
        .catch(res => {
          console.log(res);
          if (res.status == 204) {
          }
        })
        .then(err => {
          console.log(err);
        });
    },

    /**
     * @author yang
     * @desc 计算总价格
     */
    fnHandleTotal() {
      this.totalPrice = 0;
      if (this.shopList.length) {
        this.shopList.forEach((item, index) => {
          item.goods_data.forEach(childItem => {
            if (childItem.select) {
              this.totalPrice += parseFloat(childItem.quantity * childItem.goods_discount_price);

            }
          });
        });
        this.totalPrice = this.totalPrice.toFixed(2)
        let selectLen = this.shopList.filter(item => {
          return item.select;
        }).length;
        this.isSleectAll = selectLen == this.shopList.length ? true : false;
        return;
      }
      this.isSleectAll = false;
    },

    /**
     * @author yang
     * @desc 左右滑动
     */
    fnInitListScroll() {
      var container = document.querySelectorAll(".item > div");
      var _this = this;
      for (var i = 0; i < container.length; i++) {
        var x, y, X, Y, swipeX, swipeY;
        container[i].addEventListener("touchstart", function(event) {
          console.log(event);
          var targetEvent =
            event.target.innerHTML || event.srcElement.innerHTML;
          var targetShopId =
            event.target.dataset.shopid || event.srcElement.dataset.shopid;

          if (targetEvent == "删除") {
            _this.fnHandleDelete(targetShopId);
            event.stopPropagation();
            event.preventDefault();
          }
          x = event.changedTouches[0].pageX;
          y = event.changedTouches[0].pageY;
          swipeX = true;
          swipeY = true;
          if (expansion) {
            //判断是否展开，如果展开则收起
            expansion.className = "";
            event.stopPropagation();
            // event.preventDefault();
          }
        });
        container[i].addEventListener("touchmove", function(event) {
          X = event.changedTouches[0].pageX;
          Y = event.changedTouches[0].pageY;
          // 左右滑动
          if (swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0) {
            // 阻止事件冒泡
            event.stopPropagation();
            if (X - x > 10) {
              //右滑
              event.preventDefault();
              this.className = ""; //右滑收起
            }
            if (x - X > 10) {
              //左滑
              event.preventDefault();
              this.className = "swipeleft"; //左滑展开
              expansion = this;
            }
            swipeY = false;
          }
          // 上下滑动
          if (swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
            swipeX = false;
          }
        });
      }
    },

    /**
     * @author yang
     * @desc 删除购物车
     * @param _shopId 购物id
     */
    fnHandleDelete(_shopId) {
      MessageBox.confirm("是否确定删除该商品?").then(action => {
        api
          .goodscarcrud(
            "post",
            {
              uid: this.ethelWxUserInfo.id
            },
            _shopId
          )
          .catch(res => {
            console.log(res);
            if (res.status == 204) {
              this.shopList.forEach(item => {
                item.goods_data.forEach((childItem, index) => {
                  if (childItem.id == _shopId) {
                    Toast({
                      message: "删除成功",
                      position: "middle",
                      duration: 2000
                    });
                    item.goods_data.splice(index, 1);
                    this.fnHandleTotal();
                  }
                });
              });
            }
          })
          .then(err => {
            console.log(err);
          });
      });
    },

    /**
     * @desc 是否需要下拉加载
     */
    searchMore() {
      if (this.previous) {
        this.page++;
      }
    }
  },
  components: {
    Scroll,
    ComHeader,
    Loading,
    Toast,
    MessageBox,
    Indicator
  }
};
</script>
